import { FC, useEffect, useRef } from "react"
import {
  AxesHelper, PerspectiveCamera,
  PointLight, Scene, WebGLRenderer, AmbientLight, Vector3, Box3, Vector2
} from "three"
import {
  TubeModel
} from "R/models";
import {
  EffectComposer, OrbitControls,
  OutlinePass, RenderPass,
  GlitchPass
} from "three/examples/jsm/Addons.js";
import { GUI } from "dat.gui";
// 椭圆点位置
const lightPosition = new Vector3(60, 80, 100)

const Page: FC = () => {
  const container = useRef<HTMLCanvasElement>(null);
  // 基本对象
  useEffect(() => {
    const bodyele = document.body;
    const renderer = new WebGLRenderer({ canvas: container.current! }),
      camera = new PerspectiveCamera(90, bodyele.clientWidth / bodyele.clientHeight, 1, 1000),
      scene = new Scene(),
      pointLight = new PointLight(0xffffff, 10),
      axesHelper = new AxesHelper(100),
      // 后处理效果合成器
      composer = new EffectComposer(renderer)

    // 后处理通道
    const renderPass = new RenderPass(scene, camera)
    composer.addPass(renderPass)

    // 后处理包装
    const outline = new OutlinePass(
      new Vector2(bodyele.clientWidth, bodyele.clientHeight),
      scene, camera);

    outline.selectedObjects = [TubeModel];
    outline.visibleEdgeColor.set(0xffff00);
    composer.addPass(outline)
    const glitchPass = new GlitchPass(2)
    composer.addPass(glitchPass)

    renderer.setClearAlpha(.4)
    const gui = new GUI()
    pointLight.position.copy(lightPosition)
    pointLight.decay = 0
    scene.add(
      new AmbientLight(0xffffff, 1),
      axesHelper,
      pointLight,
      TubeModel
    )



    camera.position.set(15, 14, 13)
    camera.lookAt(TubeModel.position)
    new OrbitControls(camera, renderer.domElement)


    renderer.setSize(bodyele.clientWidth * devicePixelRatio, bodyele.clientHeight * devicePixelRatio)
    function roun(t?: number) {
      // renderer.render(scene, camera)
      composer.render()
      requestAnimationFrame(roun)
    }
    roun()
    return () => {
      gui.destroy()
      // renderer.dispose()
    }
  }, [])
  return <canvas ref={container}></canvas>
}
export default Page